package com.zhenyi.jiahua.index.admin;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.cjw.model.DBMap;
import com.jfinal.aop.Before;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jiahua.common.model.JhRole;
import com.jiahua.common.model.JhSchool;
import com.jiahua.common.model.JhStaff;
import com.utils.DateUtils;
import com.utils.PathUtils;
import com.utils.interceptor.TestInterceptor;
import com.zhenyi.jiahua.index.JHController;
import com.zhenyi.jiahua.task.JHBirthTask;
import com.zhenyi.jiahua.task.JHContractTask;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

/**
 * 员工管理
 * 
 * @author cen
 *
 */
public class StaffController extends JHController {

	public void search() {
		String search = getPara("keyword");
		Long staffId = getParaToLong("staffId");
		Long schoolId = getParaToLong("schoolId");
		Integer type = getParaToInt("type");

		Kv kv = Kv.create();
		// kv.set("status", 1);
		// kv.set("type", 1);
		if (StrKit.notBlank(search)) {
			kv.set("search", "%" + search + "%");
			kv.set("searchMobile", search);
		}
		if (staffId != null) {
			kv.set("staffId", staffId);
		}
		if (schoolId != null) {
			kv.set("schoolId", schoolId);
		}
		if (type != null) {
			kv.set("type", type);
		}
		Page<Record> pages = JhStaff.dao.getSubStaffs(null, kv, getPage(), PAGE_SIZE);
		renderSuccess(pages.getList());
	}

	@Override
	public void list() {
		JhStaff staff = getStaff();
		Long schoolId = getParaToLong("schoolId");
		Integer type = getParaToInt("type");
		Integer isLeave = getParaToInt("isLeave");
		Integer isMoving = getParaToInt("isMoving");
		Integer isTrying = getParaToInt("isTrying");
		String position = getPara("position");
		List<JhSchool> schools = JhSchool.dao.findAll();
		setAttr("schools", jsonObject(schools));
		setAttr("today", DateUtil.today());
		/**
		 * 搜索电话/姓名
		 */
		String search = getPara("keyword");
		Kv kv = Kv.create();
		if (StrKit.notBlank(search)) {
			kv.set("search", "%" + search + "%");
			kv.set("searchMobile", search);
			setAttr("keyword", search);
		}
		if (schoolId != null) {
			kv.set("schoolId", schoolId);
			setAttr("schoolId", schoolId);
		}
		if (StrKit.notBlank(position)) {
			kv.set("position", "%" + position + "%");
			setAttr("position", position);
		}
		if (type != null) {
			kv.set("type", type);
		}
		if (isLeave != null) {
			kv.set("isLeave", isLeave);
			setAttr("isLeave", isLeave);
		}
		if (isMoving != null) {
			kv.set("isMoving", isMoving);
			setAttr("isMoving", isMoving);
		}
		if (isTrying != null) {
			kv.set("isTrying", isTrying);
			setAttr("isTrying", isTrying);
		}

		Date entryDateStart = getTimeDate("entryDateStart");
		Date entryDateEnd = getTimeDate("entryDateEnd");
		if (entryDateStart != null && entryDateEnd != null) {
			kv.set("entryDateStart", entryDateStart);
			setAttr("entryDateStart", entryDateStart);
			kv.set("entryDateEnd", entryDateEnd);
			setAttr("entryDateEnd", entryDateEnd);
		}

		Date tryStartDateStart = getTimeDate("tryStartDateStart");
		Date tryStartDateEnd = getTimeDate("tryStartDateEnd");
		if (tryStartDateStart != null && tryStartDateEnd != null) {
			kv.set("tryStartDateStart", tryStartDateStart);
			setAttr("tryStartDateStart", tryStartDateStart);
			kv.set("tryStartDateEnd", tryStartDateEnd);
			setAttr("tryStartDateEnd", tryStartDateEnd);
		}

		Date tryEndDateStart = getTimeDate("tryEndDateStart");
		Date tryEndDateEnd = getTimeDate("tryEndDateEnd");
		if (tryEndDateStart != null && tryEndDateEnd != null) {
			kv.set("tryEndDateStart", tryEndDateStart);
			setAttr("tryEndDateStart", tryEndDateStart);
			kv.set("tryEndDateEnd", tryEndDateEnd);
			setAttr("tryEndDateEnd", tryEndDateEnd);
		}

		Date contractStartDateStart = getTimeDate("contractStartDateStart");
		Date contractStartDateEnd = getTimeDate("contractStartDateEnd");
		if (contractStartDateStart != null && contractStartDateEnd != null) {
			kv.set("contractStartDateStart", contractStartDateStart);
			setAttr("contractStartDateStart", contractStartDateStart);
			kv.set("contractStartDateEnd", contractStartDateEnd);
			setAttr("contractStartDateEnd", contractStartDateEnd);
		}

		Date contractEndDateStart = getTimeDate("contractEndDateStart");
		Date contractEndDateEnd = getTimeDate("contractEndDateEnd");
		if (contractEndDateStart != null && contractEndDateEnd != null) {
			kv.set("contractEndDateStart", contractEndDateStart);
			setAttr("contractEndDateStart", contractEndDateStart);
			kv.set("contractEndDateEnd", contractEndDateEnd);
			setAttr("contractEndDateEnd", contractEndDateEnd);
		}

		Date formalDateStart = getTimeDate("formalDateStart");
		Date formalDateEnd = getTimeDate("formalDateEnd");
		if (formalDateStart != null && formalDateEnd != null) {
			kv.set("formalDateStart", formalDateStart);
			setAttr("formalDateStart", formalDateStart);
			kv.set("formalDateEnd", formalDateEnd);
			setAttr("formalDateEnd", formalDateEnd);
		}

		Page<Record> pages = JhStaff.dao.getSubStaffs(staff, kv, getPage(), PAGE_SIZE);
		setRainbow(pages);
		setItems(JsonKit.toJson(pages.getList()));
		render("/jh/admin/staff/index.html");
	}

	private boolean isAccountAvaliable(String account, Long staffId) {
		DBMap map = new DBMap();
		map.put("account", account);
		JhStaff staff = JhStaff.dao.searchFirst(map);
		if (staff == null) {
			return true;
		}
		if (staff.getId().equals(staffId)) {
			return true;
		}
		return false;
	}

	/**
	 * 保存员工信息
	 */
	@Override
	public void submit() {
		Long staffId = getParaToLong("staffId");
		String name = getPara("name");
		String englishName = getPara("englishName");
		String code = getPara("code");
		Integer sex = getParaToInt("sex");
		String birth = getPara("birth");
		String contact1 = getPara("contact1");
		String contact2 = getPara("contact2");
		String email = getPara("email");
		String idCard = getPara("idCard");
		String minzu = getPara("minzu");
		String jiguan = getPara("jiguan");
		String hukou = getPara("hukou");
		String huji = getPara("huji");
		String marriage = getPara("marriage");
		Integer height = getParaToInt("height");
		Integer weight = getParaToInt("weight");
		String bloodType = getPara("bloodType");
		String movingType = getPara("movingType");
		Long schoolId = getParaToLong("schoolId", getStaff().getSchoolId());
		Long roleId = getParaToLong("roleId");
		Integer type = getParaToInt("type");
		// String department = getPara("department");
		// String position = getPara("position");
		Integer isTeacher = getParaToInt("isTeacher", 0);
		Integer teacherType = null;
		if (isTeacher.equals(1)) {
			teacherType = getParaToInt("teacherType", 1);
		}
		String householdType = getPara("householdType");
		String emContact = getPara("emContact");
		String emMobile = getPara("emMobile");
		String lawAddress = getPara("lawAddress");
		String address = getPara("address");
		String englishLevel = getPara("englishLevel");
		String degree = getPara("degree");
		String major = getPara("major");
		String graduation = getPara("graduation", "");
		String graduateDate = getPara("graduateDate");
		String entryDate = getPara("entryDate");
		String probationaryPeriodStart = getPara("probationaryPeriodStart");
		String probationaryPeriodEnd = getPara("probationaryPeriodEnd");
		String formalDate = getPara("formalDate");
		String contractStartDate = getPara("contractStartDate");
		String contractEndDate = getPara("contractEndDate");
		String workRecord = getPara("workRecord");
		String leaveType = getPara("leaveType");
		String leaveReason = getPara("leaveReason");
		String leaveDate = getPara("leaveDate");
		String account = getPara("account");
		String password = getPara("password");
		String internSalary = getPara("internSalary", "0");
		String probationSalary = getPara("probationSalary", "0");
		String formalSalary = getPara("formalSalary", "0");
		String bankAccount = getPara("bankAccount");
		Integer isLeave = getParaToInt("isLeave", 0);
		Integer isPartTime = getParaToInt("isPartTime", 0);
		String signType = getPara("signType");
		Integer isTempory = getParaToInt("isTempory");
		String mark = getPara("mark");
		Integer isMoving = getParaToInt("isMoving");

		String certificate = getPara("certificate");
		String bank = getPara("bank");

		String position = getPara("position");

		if (!isAccountAvaliable(account, staffId)) {
			renderMsg("登录账号重复");
			return;
		}

		boolean isNew = staffId == null;
		JhStaff info = isNew ? new JhStaff() : JhStaff.dao.findById(staffId);
		if (!isNew && info == null) {
			renderFailure(404, "staff not found");
			return;
		}
		info.setName(name);
		info.setEnglishName(englishName);
		info.setCode(code);
		info.setSex(sex);
		if (StrKit.notBlank(birth)) {
			info.setBirth(DateUtil.parse(birth, "yyyy-MM-dd"));
		}
		info.setContact1(contact1);
		info.setContact2(contact2);
		info.setEmail(email);
		info.setIdCard(idCard);
		info.setMinzu(minzu);
		info.setJiguan(jiguan);
		info.setHukou(hukou);
		info.setHuji(huji);
		info.setMarriage(marriage);
		info.setHeight(height);
		info.setWeight(weight);
		info.setBloodType(bloodType);
		info.setSchoolId(schoolId);
		info.setRoleId(roleId);
		info.setType(type);
		// info.setDepartment(department);
		// info.setPosition(position);
		info.setIsTeacher(isTeacher);
		info.setTeacherType(teacherType);
		info.setHouseholdType(householdType);
		info.setEmContact(emContact);
		info.setEmMobile(emMobile);
		info.setLawAddress(lawAddress);
		info.setAddress(address);
		info.setEnglishLevel(englishLevel);
		info.setDegree(degree);
		info.setMajor(major);
		info.setGraduation(graduation);
		info.setLeaveReason(leaveReason);
		info.setAccount(account);
		info.setPassword(password);
		info.setInternSalary(BigDecimal.valueOf(Double.valueOf(internSalary)));
		info.setProbationSalary(BigDecimal.valueOf(Double.valueOf(probationSalary)));
		info.setFormalSalary(BigDecimal.valueOf(Double.valueOf(formalSalary)));
		info.setBankAccount(bankAccount);
		if (StrKit.notBlank(graduateDate)) {
			info.setGraduateDate(DateUtil.parse(graduateDate, "yyyy-MM-dd"));
		}
		if (StrKit.notBlank(entryDate)) {
			info.setEntryDate(DateUtil.parse(entryDate, "yyyy-MM-dd"));
		}
		if (StrKit.notBlank(probationaryPeriodStart)) {
			info.setProbationaryPeriodStart(DateUtil.parse(probationaryPeriodStart, "yyyy-MM-dd"));
		}
		if (StrKit.notBlank(probationaryPeriodEnd)) {
			info.setProbationaryPeriodEnd(DateUtil.parse(probationaryPeriodEnd, "yyyy-MM-dd"));
		}
		if (StrKit.notBlank(formalDate)) {
			info.setFormalDate(DateUtil.parse(formalDate, "yyyy-MM-dd"));
		}
		if (StrKit.notBlank(contractStartDate)) {
			info.setContractStartDate(DateUtil.parse(contractStartDate, "yyyy-MM-dd"));
		}
		if (StrKit.notBlank(contractEndDate)) {
			info.setContractEndDate(DateUtil.parse(contractEndDate, "yyyy-MM-dd"));
		}
		if (StrKit.notBlank(leaveDate)) {
			info.setLeaveDate(DateUtil.parse(leaveDate, "yyyy-MM-dd"));
		}
		info.setWorkRecord(workRecord);
		info.setLeaveType(leaveType);
		info.setIsLeave(isLeave);
		info.setIsPartTime(isPartTime);
		info.setSignType(signType);
		info.setIsTempory(isTempory);
		info.setIsMoving(isMoving);
		info.setMark(mark);
		info.setMovingType(movingType);
		info.setPosition(position);
		info.setCertificate(certificate);

		info.setBank(bank);

		boolean flag = isNew ? info.save() : info.update();
		if (flag) {
			renderSuccess();
		} else {
			renderFailure();
		}

	}

	@Override
	public void info() {
		Long staffId = getParaToLong("staffId");
		JhStaff staff = staffId == null ? new JhStaff() : JhStaff.dao.findById(staffId);

		List<JhSchool> schools = JhSchool.dao.findAll();
		String today = DateUtil.today();

		List<JhRole> roles = JhRole.dao.findAll();

		setInfoItem(staff);
		setAttr("schools", JSONUtil.toJsonStr(schools));
		setAttr("today", today);
		setAttr("roles", JSONUtil.toJsonStr(roles));
		render("/jh/admin/staff/info.html");
	}

	/**
	 * 删除员工
	 */
	@Override
	public void delete() {
		Long staffId = getParaToLong("staffId");
		if (staffId == null) {
			LogKit.warn("del staff error ,staffId: " + staffId);
			renderError(404);
			return;
		}
		JhStaff staff = JhStaff.dao.findById(staffId);
		if (staff == null) {
			LogKit.warn("del staff error ,staffId: " + staffId);
			renderError(404);
			return;
		}
		staff.setFlag(1);
		staff.update();
		renderSuccess();
	}

	@Before(TestInterceptor.class)
	public void birth() {
		new JHBirthTask().run();
		renderSuccess();
	}

	@Before(TestInterceptor.class)
	public void contract() {
		new JHContractTask().run();
		renderSuccess();
	}

	public void download() {
		SqlPara sqlPara = Db.use("jiahua").getSqlPara("JHDownloadStaff");
		List<JhStaff> items = JhStaff.dao.find(sqlPara);
		ArrayList<List<String>> arrayList = new ArrayList<>();
		List<String> title = CollUtil.newArrayList("姓名", "英文名", "员工编号", "性别", "生日", "身份证", "民族", "籍贯", "户口所在地", "户籍类别",
				"婚姻状态", "身高", "体重", "血型", "联系电话1", "联系电话2", "电子邮箱", "紧急联系人", "紧急联系电话", "英语水平", "法定联系地址", "现住地", "学历",
				"专业", "毕业学校", "毕业日期", "入职日期", "试用期(起)", "试用期(止)", "转正日期", "合同时效(起)", "合同失效(止)", "用工备案", "实习工资", "试用期工资",
				"转正工资", "银行账号", "开户行", "校区", "岗位", "是否老师", "教师类型", "是否离职", "离职日期", "离职原因", "离职类别");
		arrayList.add(title);
		for (JhStaff jhStaff : items) {
			String name = jhStaff.getName();
			String englishName = jhStaff.getEnglishName();
			String code = jhStaff.getCode();
			String sex = jhStaff.getSex() == null ? "" : jhStaff.getSex().equals(1) ? "男" : "女";
			String birth = DateUtil.format(jhStaff.getBirth(), DateUtils.YYYYMMDD);
			String idCard = jhStaff.getIdCard();
			String minzu = jhStaff.getMinzu();
			String jiguan = jhStaff.getJiguan();
			String huku = jhStaff.getHukou();
			String huji = jhStaff.getHuji();
			String marriage = jhStaff.getMarriage();
			String height = jhStaff.getHeight() == null ? "" : jhStaff.getHeight() + "";
			String weight = jhStaff.getWeight() == null ? "" : jhStaff.getWeight() + "";
			String bloodType = jhStaff.getBloodType();
			String contact1 = jhStaff.getContact1();
			String contact2 = jhStaff.getContact2();
			String email = jhStaff.getEmail();
			String emContact = jhStaff.getEmContact();
			String emMobile = jhStaff.getEmMobile();
			String englishLevel = jhStaff.getEnglishLevel();
			String lawAddress = jhStaff.getLawAddress();
			String address = jhStaff.getAddress();
			// String department = "";
			String degree = jhStaff.getDegree();
			String major = jhStaff.getMajor();
			String graduation = jhStaff.getGraduation();
			String graduateDate = DateUtil.format(jhStaff.getGraduateDate(), DateUtils.YYYYMMDD);
			String entryDate = DateUtil.format(jhStaff.getEntryDate(), DateUtils.YYYYMMDD);
			String probationaryPeriodStart = DateUtil.format(jhStaff.getProbationaryPeriodStart(), DateUtils.YYYYMMDD);
			String probationaryPeriodEnd = DateUtil.format(jhStaff.getProbationaryPeriodEnd(), DateUtils.YYYYMMDD);
			String formalDate = DateUtil.format(jhStaff.getFormalDate(), DateUtils.YYYYMMDD);
			String contractStartDate = DateUtil.format(jhStaff.getContractStartDate(), DateUtils.YYYYMMDD);
			String contractEndDate = DateUtil.format(jhStaff.getContractEndDate(), DateUtils.YYYYMMDD);
			String workRecord = jhStaff.getWorkRecord();

			String school = JhSchool.dao.findById(jhStaff.getSchoolId()).getName();
			String internSalary = jhStaff.getInternSalary().toString();
			String probationSalary = jhStaff.getProbationSalary().toString();
			String formalSalary = jhStaff.getFormalSalary().toString();
			String bankAccount = jhStaff.getBankAccount();
			String bank = jhStaff.getBank();
			String teacherType = jhStaff.getTeacherType() == null ? ""
					: jhStaff.getTeacherType().equals(1) ? "中教" : "外教";
			String leaveType = jhStaff.getLeaveType();
			String leaveReason = jhStaff.getLeaveReason();
			String leaveDate = DateUtil.format(jhStaff.getLeaveDate(), DateUtils.YYYYMMDD);
			String isLeave = jhStaff.getIsLeave().equals(0) ? "在职" : "离职";
			if (jhStaff.getIsLeave().equals(0)) {
				leaveType = "";
				leaveReason = "";
				leaveDate = "";
			} else {
			}
			String isTeacher = jhStaff.getIsTeacher().equals(0) ? "否" : "是";
			String position = "";
			Integer type = jhStaff.getType();
			if (type != null) {
				if (type.equals(JhStaff.TYPE_CC)) {
					position = "CC";
				} else if (type.equals(JhStaff.TYPE_FIN)) {
					position = "财务 ";
				} else if (type.equals(JhStaff.TYPE_FRONT)) {
					position = "前台";
				} else if (type.equals(JhStaff.TYPE_PD)) {
					position = "人事";
				} else if (type.equals(JhStaff.TYPE_TA)) {
					position = "助教";
				} else if (type.equals(JhStaff.TYPE_TEACHER)) {
					position = "教师";
				} else if (type.equals(JhStaff.TYPE_TMK)) {
					position = "TMK";
				} else if (type.equals(JhStaff.TYPE_TUIGUANG)) {
					position = "推广";
				}
			}
			List<String> row = CollUtil.newArrayList(name, englishName, code, sex, birth, idCard, minzu, jiguan, huku,
					huji, marriage, height, weight, bloodType, contact1, contact2, email, emContact, emMobile,
					englishLevel, lawAddress, address, degree, major, graduation, graduateDate, entryDate,
					probationaryPeriodStart, probationaryPeriodEnd, formalDate, contractStartDate, contractEndDate,
					workRecord, internSalary, probationSalary, formalSalary, bankAccount, bank, school, position,
					isTeacher, teacherType, isLeave, leaveDate, leaveReason, leaveType);
			arrayList.add(row);
		}
		String now = DateUtil.now();
		now = now.replace("-", "");
		now = now.replace(":", "");
		now = now.replace(" ", "");
		String name = "员工信息-" + now + ".xlsx";
		String path = PathUtils.getFile("jh", "temp", "excel", name);
		ExcelWriter writer = ExcelUtil.getWriter(path);
		writer.write(arrayList);
		writer.close();
		File file = new File(path);
		renderFile(file);
	}

}
